package com.gh.mp.eduservice.controller;

import com.gh.mp.edu.utils.JwtUtils;
import com.gh.mp.eduservice.entity.UcenterMember;
import com.gh.mp.eduservice.service.UcenterMemberService;
import com.gh.mp.eduservice.util.ConstantWxUtils;
import com.gh.mp.eduservice.util.HttpClientUtils;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @Author Eric
 * @Date 2021/5/16 13:55
 * @Version 1.0
 */
@Controller
@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService ucenterMemberService;
    /**
     * 获取扫描人信息
     * @return
     */
    @GetMapping("callback")
    public String callback(String code,String state){
        try {
            //那种code请求微信固定地址,得到两个值access_token和openid
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            String accessTokenUrl = String.format(baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code);
            //请求拼接好的地址，得到两个值access_token和openid使用httpclient技术
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            Gson gson=new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String accessToken = (String) mapAccessToken.get("access_token");
            String openid = (String) mapAccessToken.get("openid");
            //判断数据库有没有openid
            UcenterMember member=ucenterMemberService.getOpenIdMember(openid);
            if(member==null){
                //代表表里面没有相同的数据，所以我们要添加到数据库
                //拿着access_token和openid再去请求微信提供的固定地址，获取扫描人信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
                //发送请求
                String userInfo = HttpClientUtils.get(userInfoUrl);
                HashMap<String,Object> userInfoMap= gson.fromJson(userInfo, HashMap.class);//这是用户信息
                String nickname = (String) userInfoMap.get("nickname");//昵称
                String headimgurl = (String) userInfoMap.get("headimgurl");//头像
                Double sex = (Double) userInfoMap.get("sex");
                member=new UcenterMember();
                member.setAvatar(headimgurl);
                member.setSex(new Double(sex).intValue());
                member.setNickname(nickname);
                member.setOpenid(openid);
                ucenterMemberService.save(member);
            }
            String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            return "redirect:http://localhost:3000?token="+token;
        }catch (Exception e){
            e.printStackTrace();
        }

        return "";

    }

    /**
     * 获取二维码
     * @return
     */
    @GetMapping("login")
    public String getWxCode(){

        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
        "?appid=%s" +
        "&redirect_uri=%s" +
        "&response_type=code" +
        "&scope=snsapi_login" +
        "&state=%s" +
        "#wechat_redirect";

        //对redirect_url进行URLEncoder编码
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 防止csrf攻击（跨站请求伪造攻击）
        //String state = UUID.randomUUID().toString().replaceAll("-", "");//一般情况下会使用一个随机数
        String state = "imhelen";//为了让大家能够使用我搭建的外网的微信回调跳转服务器，这里填写你在ngrok的前置域名

        String ericUrl = String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                ConstantWxUtils.WX_OPEN_REDIRECT_URL,
                "Eric",
                redirectUrl
        );

        return "redirect:"+ericUrl;
    }
}
